package com.edais.service.imp.gift;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.edais.dao.ActivityDao;
import com.edais.dao.SystemSettingDao;
import com.edais.domain.UserActivityUpFrozenInfo;
import com.edais.domain.gift.GiftPackageOrder;
import com.edais.persistence.gift.GiftPackageOrderMapper;
import com.edais.service.gift.GiftPackageOrderService;
import com.edais.util.CommonUtil;
import com.edais.util.Consts;

import com.alibaba.fastjson.JSONObject;

@Service
public class GiftPackageOrderServiceImpl implements GiftPackageOrderService {
	private static final Log logger = LogFactory.getLog(GiftPackageOrderServiceImpl.class);

	@Autowired
	private GiftPackageOrderMapper giftPackageOrderMapper;

	@Autowired
	private SystemSettingDao systemSettingDao;
	
	@Autowired
	private ActivityDao activityDao;

	@Override
	public Map<String, Object> queryGiftPackageOrderByCardNo(String cardNo, String logInfo) throws Exception {
		Map<String, Object> retMap = new HashMap<String, Object>();
		BigDecimal expireAmount = BigDecimal.ZERO;

		GiftPackageOrder giftPackageOrder = giftPackageOrderMapper.queryGiftPackageOrderByCardNo(cardNo);
		if (giftPackageOrder == null) {
			logger.info(logInfo + "giftPackageOrder不存在，K码未激活");
			retMap.put("isActivation", 1);
			retMap.put("isActivationName", "未激活");
			retMap.put("rescode", Consts.SUCCESS_CODE);
			retMap.put("resmsg_cn", "");
			return retMap;
		}
		retMap.put("isActivation", 0);
		retMap.put("isActivationName", "已激活");
		// 礼包信息(礼包是否到期，礼包到期本金)
		String status = giftPackageOrder.getStatus();
		

		if (GiftPackageOrder.STATUS_SUCCESS.equals(status)) {// 交易完成和交易失败都是已过期
			retMap.put("isExpire", 0);
			retMap.put("isExpireName", "已过期");
			retMap.put("isFrozen", "0");
			retMap.put("isFrozenName", "未冻结");
			if(StringUtils.isNotBlank(giftPackageOrder.getKcodeMoney())){
				BigDecimal investAmount1 = new BigDecimal(giftPackageOrder.getKcodeMoney());
				expireAmount = expireAmount.add(investAmount1);
			}
			retMap.put("expireAmount", expireAmount);
			retMap.put("rescode", Consts.SUCCESS_CODE);
			retMap.put("resmsg_cn", "");
			return retMap;
		} 
		retMap.put("isExpire", 1);
		retMap.put("isExpireName", "未过期");
		
		if (GiftPackageOrder.STATUS_FROZEN.equals(status)) {// 冻结状态
			retMap.put("isFrozen", 1);
			retMap.put("isFrozenName", "已冻结");
			retMap.put("expireAmount", expireAmount);
			retMap.put("rescode", Consts.SUCCESS_CODE);
			retMap.put("resmsg_cn", "");
			return retMap;
		} 
		retMap.put("expireAmount", expireAmount);
		retMap.put("isFrozen", "0");
		retMap.put("isFrozenName", "未冻结");
		
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg_cn", "");
		return retMap;
	}

	@Override
	public Map<String, Object> giftPackageFrozen(String cardNo, String logInfo, int type) throws Exception {
		// TODO Auto-generated method stub
		Map<String, Object> retMap = new HashMap<String, Object>();
		GiftPackageOrder giftPackageOrder = giftPackageOrderMapper.queryGiftPackageOrderByCardNo(cardNo);
		String error = "";
		if (giftPackageOrder == null) {
			error = "礼包订单不存在，carNo错误或者K码未被激活";
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			retMap.put("resmsg_cn", error);
			return retMap;
		}
		String status = giftPackageOrder.getStatus();// 状态
		String upStatus = "";// 跟新后的状态
		String statusName=this.getStatusName(status);
		
		if (type == 1) { // 解冻
			if (!GiftPackageOrder.STATUS_FROZEN.equals(status)) {// 不是冻结状态不能解冻直接返回
				error = "礼包当前状态为:"+statusName+",不能进行解冻操作";
				retMap.put("rescode", Consts.ERROR_CODE);
				retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
				retMap.put("resmsg_cn", error);
				return retMap;
			}
			upStatus = GiftPackageOrder.STATUS_INIT;

		} else if (type == 2) {// 冻结
			if (!GiftPackageOrder.STATUS_INIT.equals(status)) {// 不是初始状态不能冻结
				error = "礼包当前状态为："+statusName+",不能进行冻结操作";
				retMap.put("rescode", Consts.ERROR_CODE);
				retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
				retMap.put("resmsg_cn", error);
				return retMap;
			}
			upStatus = GiftPackageOrder.STATUS_FROZEN;

		}
		
		
		logger.info("判断预冻结是否有该订单 ，有的话改为已处理");
		// 获取预冻结数据
		Map<String,Object>parmMap=new HashMap<String, Object>();
		parmMap.put("card_no", cardNo);
		UserActivityUpFrozenInfo info = activityDao.queryUserUpForzenInfoByParm(parmMap);
		// 如果是未处理的情况。则更新成 已处理1 0 未处理
		if (info != null) {
			if ("0".equals(info.getIsValid())) {
				info.setIsValid("1");
				activityDao.updateUserUpForzenInfo(info);
			}
		}
		

		logger.info(logInfo + "开始更新礼包订单状态 当前的状态为status==" + status + "修改后的状态upStatus==" + upStatus);

		Map<String, Object> updateMap = new HashMap<String, Object>();
		updateMap.put("type", type);
		updateMap.put("cardNo", cardNo);
		updateMap.put("status", upStatus);

		giftPackageOrderMapper.updateOrderStatusByMap(updateMap);

		logger.info(logInfo + "更新成功");
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg_cn", "操作成功");

		return retMap;
	}

	@Override
	public JSONObject giftPackageJoinMyAccount(String userId, String phone) throws Exception {

		JSONObject resjb = new JSONObject();
		// 礼包数量+礼包开关 +礼包金额w
		String giftPackageSwitch = "Y";// 礼包开关 默认开
		String giftPackageSum = "0";// 礼包的数量 默认是0（状态为0的礼包订单数量和）
		String giftPackageAmount = "0";// 礼包的金额

		/** 获取礼包开关 **/
		giftPackageSwitch = systemSettingDao.getSystemSettingValueByName("gift_on-off");
		if (StringUtils.isBlank(giftPackageSwitch)) {
			giftPackageSwitch = "Y";
		}
		/** 获取礼包数量 **/
		Map<String, Object> queryMap = new HashMap<String, Object>();
		queryMap.put("userId", userId);
		queryMap.put("phone", phone);
		queryMap.put("status", GiftPackageOrder.STATUS_INIT);
		giftPackageSum = String.valueOf(giftPackageOrderMapper.getGiftPackageOrderByMap(queryMap));

		/** 获取礼包金额 **/

		resjb.put("giftPackageSwitch", giftPackageSwitch);
		resjb.put("giftPackageSum", giftPackageSum);
		return resjb;
	}

	@Override
	public GiftPackageOrder loadGiftPackageOrder(Long id) {
		return giftPackageOrderMapper.selectByPrimaryKey(id);
	}

	@Override
	public GiftPackageOrder selectGiftPackageOrder(Map<String, Object> params) {
		return giftPackageOrderMapper.selectGiftPackageOrder(params);
	}

	@Override
	public boolean isGiftPackagetOrLiCai(String cardNo, String logInfo) throws Exception {
		int count = giftPackageOrderMapper.queryCountKcodeLicai(cardNo);

		if (count > 0) {// 走的是理财
			logger.info(logInfo + "走理财");
			return true;
		}
		logger.info(logInfo + "走礼包");
		return false;

	}

	@Override
	public Map<String, Object> cancelKcodeGiftPackage(String logInfo, Map<String, Object> params) throws Exception {
		Map<String, Object> retMap = new HashMap<String, Object>();
		logger.info(logInfo + "取消K码礼包开始");
		
		GiftPackageOrder giftPackageOrder = giftPackageOrderMapper.queryGiftPackageOrderByCardNo((String)params.get("kcodeCardNo"));
		String error = "";
		if (giftPackageOrder == null) {
			error = "礼包订单不存在，carNo错误或者K码未被激活";
			logger.error(logInfo + "取消K码礼包异常：" + error);
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			retMap.put("resmsg_cn", "礼包订单不存在，carNo错误或者K码未被激活");
			return retMap;
		}
		
		String status = giftPackageOrder.getStatus();// 状态
		
		if (GiftPackageOrder.STATUS_SUCCESS.equals(status)||GiftPackageOrder.STATUS_FAILED.equals(status)) {// 不是冻结状态不能解冻直接返回
			error = "礼包当前状态为:"+this.getStatusName(status)+",不能进行退货操作";
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			retMap.put("resmsg_cn",error);
			return retMap;

		}
		
		Map coreMap = CommonUtil.invokeCore(logInfo, "kcodeGiftPackageCancelService", params);
		if (coreMap == null || !"00000".equals(coreMap.get("rescode"))) {
			logger.error(logInfo + "取消K码礼包异常：" + coreMap.get("resmsg"));
			retMap.put("rescode", Consts.ERROR_CODE);
			retMap.put("resmsg", Consts.ErrorMsg.MSG00001);
			retMap.put("resmsg_cn", "取消K码礼包异常");
			return retMap;
		}
		logger.info(logInfo + "取消K码礼包结束");
		retMap.put("rescode", Consts.SUCCESS_CODE);
		retMap.put("resmsg", "");
		retMap.put("resmsg_cn", "");
		logger.info(logInfo + "结束");
		return retMap;
	}
	
	/**
	 * 根据状态获取状态名称
	 * @param status
	 * @return
	 */
	private String getStatusName(String status){
		String statusName;
		if(GiftPackageOrder.STATUS_INIT.equals(status)){
			statusName="初始";
			
		}else if(GiftPackageOrder.STATUS_SUCCESS.equals(status)){
			statusName="交易完成";
		}else if(GiftPackageOrder.STATUS_FAILED.equals(status)){
			statusName="交易失败";
		}else if(GiftPackageOrder.STATUS_FROZEN.equals(status)){
			statusName="冻结";
		}else{
			statusName="";
		}
		return statusName;
	}
}
